package com.xmy.cultivate.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.xmy.cultivate.entity.*;
import com.xmy.cultivate.exception.CommonException;
import com.xmy.cultivate.mapper.CourseSchedulingMapper;
import com.xmy.cultivate.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xmy.cultivate.util.DateUtil;
import com.xmy.cultivate.util.ResultCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;

/**
 * <p>
 * 排课表 服务实现类
 * </p>
 *
 * @author min
 * @since 2022-07-28
 */
@Service
public class CourseSchedulingServiceImpl extends ServiceImpl<CourseSchedulingMapper, CourseScheduling> implements ICourseSchedulingService {

    @Autowired
    ICourseSchedulingDetailService iCourseSchedulingDetailService;
    @Autowired
    ICourseSchedulingRedoService iCourseSchedulingRedoService;

    @Autowired
    IGradeService iGradeService;

    @Autowired
    IOrganizationService iOrganizationService;

    @Autowired
    IClassRoomService iClassRoomService;

    @Autowired
    ICourseService iCourseService;

    @Autowired
    IStaffService iStaffService;

    @Autowired
    ISubjectsService iSubjectsService;

    @Transactional
    public boolean saveTo(CourseScheduling courseScheduling) throws ParseException {

        Grade grade = iGradeService.getById(courseScheduling.getGradeId());
        if(grade == null){
            throw new CommonException(ResultCode.GRADE_NOT);
        }

        courseScheduling.setSchoolId(grade.getSchoolId());
        courseScheduling.setCourseId(grade.getCourseId());

        if(courseScheduling.getArrangingWay() == 1){
            String[] strartTime = courseScheduling.getTimeStart().split(":");
            String[] endTime = courseScheduling.getTimeEnd().split(":");
            courseScheduling.setStartHouse(strartTime[0]);
            courseScheduling.setStartHouse(strartTime[1]);
            courseScheduling.setStartMinute(endTime[0]);
            courseScheduling.setEndMinute(endTime[1]);
        }

        this.save(courseScheduling);

        //排课方式
        Integer arrangingWay = courseScheduling.getArrangingWay();
        //自由排课
        if(arrangingWay == 1){

            String attendClassDates = courseScheduling.getAttendClassDates();
            if(StringUtils.isBlank(attendClassDates)){
                throw new CommonException(ResultCode.AttendClassDateNotNull);
            }

            Organization shooleInfo = iOrganizationService.getById(courseScheduling.getSchoolId());
            if(shooleInfo == null){
                throw new CommonException(ResultCode.SchoolNotNull);
            }
            ClassRoom classRoom = iClassRoomService.getById(courseScheduling.getClassRoomId());
            if(classRoom == null){
                throw new CommonException(ResultCode.ClassRoomNotNull);
            }
            Course course = iCourseService.getById(courseScheduling.getCourseId());
            if(course == null){
                throw new CommonException(ResultCode.CourseNotNull);
            }
            Staff teacher = iStaffService.getById(courseScheduling.getTeacherId());
            if(teacher == null){
                throw new CommonException(ResultCode.TeacerNo);
            }

            UpdateWrapper<Grade> gradeUpdateWrapper = new UpdateWrapper<>();
            gradeUpdateWrapper.eq("id",grade.getId()).set("teacher_id",teacher.getId()).set("class_room_id",classRoom.getId());
            iGradeService.update(null,gradeUpdateWrapper);

            Staff assistant = iStaffService.getById(courseScheduling.getAssistantId());
            Subjects subjects = iSubjectsService.getById(course.getSubjectsId());

            //自由排课
            List<CourseSchedulingDetail> courseSchedulingDetailList = new ArrayList<>();
            List<String> datesList = Arrays.asList(attendClassDates.split(","));
            Iterator<String> iterator = datesList.iterator();
            while (iterator.hasNext()){
                String date = iterator.next();
                CourseSchedulingDetail courseSchedulingDetail = new CourseSchedulingDetail();

                courseSchedulingDetail.setCourseSchedulingId(courseScheduling.getId());
                courseSchedulingDetail.setSchoolDate(DateUtil.StrToDate(date));
                courseSchedulingDetail.setTimeStart(courseScheduling.getTimeStart());
                courseSchedulingDetail.setTimeEnd(courseScheduling.getTimeEnd());

                LocalDateTime startDateTime = DateUtil.StrToDateTime(date + "T"+ courseScheduling.getTimeStart()+":00");
                LocalDateTime endDateTime = DateUtil.StrToDateTime(date + "T"+ courseScheduling.getTimeEnd()+":00");
                courseSchedulingDetail.setStartDateTime(startDateTime);
                courseSchedulingDetail.setEndDateTime(endDateTime);
                courseSchedulingDetail.setArrangingWay(courseScheduling.getArrangingWay());

                //校区
                courseSchedulingDetail.setSchoolId(grade.getSchoolId());
                courseSchedulingDetail.setSchoolName(shooleInfo.getName());
                //班级
                courseSchedulingDetail.setGradeId(courseScheduling.getGradeId());
                courseSchedulingDetail.setGradeName(grade.getName());
                //老师
                courseSchedulingDetail.setTeacherId(courseScheduling.getTeacherId());
                courseSchedulingDetail.setTeacherName(teacher.getName());
                //助教
                courseSchedulingDetail.setAssistantId(courseScheduling.getAssistantId());
                if(assistant !=null){
                    courseSchedulingDetail.setAssistantName(assistant.getName());
                }

                //教室
                courseSchedulingDetail.setClassRoomId(courseScheduling.getClassRoomId());
                courseSchedulingDetail.setClassRoomName(classRoom.getName());
                //科目
                courseSchedulingDetail.setSubjectsId(course.getSubjectsId());
                if(subjects != null){
                    courseSchedulingDetail.setSubjectsName(subjects.getName());
                }

                //课程
                courseSchedulingDetail.setCourseId(grade.getCourseId());
                courseSchedulingDetail.setCourseName(course.getName());


                courseSchedulingDetailList.add(courseSchedulingDetail);
                //System.out.print(date);
            }
            if(courseSchedulingDetailList.size()>0){
                iCourseSchedulingDetailService.saveBatch(courseSchedulingDetailList,courseSchedulingDetailList.size());
            }

        }else if(arrangingWay == 2){
            //重复排课
            List<CourseSchedulingRedo> courseSchedulingRedoList = courseScheduling.getRedoList();
            Iterator<CourseSchedulingRedo> iterator = courseSchedulingRedoList.iterator();
            while (iterator.hasNext()){
                //自由排课
                List<CourseSchedulingDetail> courseSchedulingDetailList = new ArrayList<>();

                CourseSchedulingRedo courseSchedulingRedo = iterator.next();
                //System.out.print(courseSchedulingRedo);

                courseSchedulingRedo.setSchoolId(grade.getSchoolId());
                courseSchedulingRedo.setCourseId(grade.getCourseId());
                courseSchedulingRedo.setGradeId(courseScheduling.getGradeId());
                Organization shooleInfo = iOrganizationService.getById(courseSchedulingRedo.getSchoolId());
                if(shooleInfo == null){
                    throw new CommonException(ResultCode.SchoolNotNull);
                }
                ClassRoom classRoom = iClassRoomService.getById(courseSchedulingRedo.getClassRoomId());
                if(classRoom == null){
                    throw new CommonException(ResultCode.ClassRoomNotNull);
                }
                Course course = iCourseService.getById(courseSchedulingRedo.getCourseId());
                if(course == null){
                    throw new CommonException(ResultCode.CourseNotNull);
                }
                Staff teacher = iStaffService.getById(courseSchedulingRedo.getTeacherId());
                if(teacher == null){
                    throw new CommonException(ResultCode.TeacerNo);
                }

                Staff assistant = iStaffService.getById(courseSchedulingRedo.getAssistantId());
                Subjects subjects = iSubjectsService.getById(course.getSubjectsId());



                courseSchedulingRedo.setCourseSchedulingId(courseScheduling.getId());
                //courseSchedulingRedo.setGradeId(courseScheduling.getGradeId());
                courseSchedulingRedo.setArrangingWay(courseScheduling.getArrangingWay());

                String[] strartTime = courseSchedulingRedo.getTimeStart().split(":");
                String[] endTime = courseSchedulingRedo.getTimeEnd().split(":");
                courseSchedulingRedo.setStartHouse(strartTime[0]);
                courseSchedulingRedo.setStartHouse(strartTime[1]);
                courseSchedulingRedo.setStartMinute(endTime[0]);
                courseSchedulingRedo.setEndMinute(endTime[1]);



                iCourseSchedulingRedoService.save(courseSchedulingRedo);
                List<Integer> weekDates = courseSchedulingRedo.getWeekDatesList();
                if(courseSchedulingRedo.getEndMode()==1){
                    //按日期

                    Long diffDateNum =  DateUtil.diffDays(courseSchedulingRedo.getStartDate(),courseSchedulingRedo.getEndDate());
                    //System.out.println();
                    //System.out.print("diffDateNum:"+diffDateNum);
                    for (Integer i=0;i<=diffDateNum;i++){
                        //添加天数
                        LocalDate nowDate =  courseSchedulingRedo.getStartDate().plusDays(i);
                        //System.out.println();
                        //System.out.print("nowDate:"+nowDate);
                        Integer weekIndex =  DateUtil.getWeekIndex(nowDate);
                        //System.out.println();
                        //System.out.print("weekIndex:"+weekIndex);
                        if(weekDates.contains(weekIndex)){
                            //存在
                            CourseSchedulingDetail courseSchedulingDetail = new CourseSchedulingDetail();
                            courseSchedulingDetail.setCourseSchedulingId(courseScheduling.getId());
                            courseSchedulingDetail.setSchoolDate(nowDate);
                            courseSchedulingDetail.setTimeStart(courseSchedulingRedo.getTimeStart());
                            courseSchedulingDetail.setTimeEnd(courseSchedulingRedo.getTimeEnd());

                            LocalDateTime startDateTime = DateUtil.StrToDateTime(nowDate + "T"+ courseSchedulingRedo.getTimeStart()+":00");
                            LocalDateTime endDateTime = DateUtil.StrToDateTime(nowDate + "T"+ courseSchedulingRedo.getTimeEnd()+":00");

                            courseSchedulingDetail.setStartDateTime(startDateTime);
                            courseSchedulingDetail.setEndDateTime(endDateTime);

                            courseSchedulingDetail.setArrangingWay(courseScheduling.getArrangingWay());//排课方式

                            //校区
                            courseSchedulingDetail.setSchoolId(grade.getSchoolId());
                            courseSchedulingDetail.setSchoolName(shooleInfo.getName());
                            //班级
                            courseSchedulingDetail.setGradeId(courseSchedulingRedo.getGradeId());
                            courseSchedulingDetail.setGradeName(grade.getName());
                            //老师
                            courseSchedulingDetail.setTeacherId(courseSchedulingRedo.getTeacherId());
                            courseSchedulingDetail.setTeacherName(teacher.getName());
                            //助教
                            courseSchedulingDetail.setAssistantId(courseSchedulingRedo.getAssistantId());
                            if(assistant !=null){
                                courseSchedulingDetail.setAssistantName(assistant.getName());
                            }

                            //教室
                            courseSchedulingDetail.setClassRoomId(courseSchedulingRedo.getClassRoomId());
                            courseSchedulingDetail.setClassRoomName(classRoom.getName());
                            //科目
                            courseSchedulingDetail.setSubjectsId(course.getSubjectsId());
                            if(subjects != null){
                                courseSchedulingDetail.setSubjectsName(subjects.getName());
                            }

                            //课程
                            courseSchedulingDetail.setCourseId(grade.getCourseId());
                            courseSchedulingDetail.setCourseName(course.getName());

                            courseSchedulingDetailList.add(courseSchedulingDetail);
                        }else {
                            //System.out.println();
                            //System.out.print("dates.contains，不存在");
                        }
                    }
                }else if(courseSchedulingRedo.getEndMode()==2){
                    //按期数
                    Integer count = courseSchedulingRedo.getExpectNum();
                    Integer i = 0;
                    boolean flag = true;
                    while (flag){
                        LocalDate nowDate =  courseSchedulingRedo.getStartDate().plusDays(i);
                        Integer weekIndex =  DateUtil.getWeekIndex(nowDate);
                        if(weekDates.contains(weekIndex)){
                            //存在
                            CourseSchedulingDetail courseSchedulingDetail = new CourseSchedulingDetail();

                            courseSchedulingDetail.setCourseSchedulingId(courseScheduling.getId());
                            courseSchedulingDetail.setSchoolDate(nowDate);
                            courseSchedulingDetail.setTimeStart(courseSchedulingRedo.getTimeStart());
                            courseSchedulingDetail.setTimeEnd(courseSchedulingRedo.getTimeEnd());
                            courseSchedulingDetail.setArrangingWay(courseScheduling.getArrangingWay());//排课方式
                            courseSchedulingDetail.setSubjectsId(courseSchedulingRedo.getSubjectsId());

                            //校区
                            courseSchedulingDetail.setSchoolId(grade.getSchoolId());
                            courseSchedulingDetail.setSchoolName(shooleInfo.getName());
                            //班级
                            courseSchedulingDetail.setGradeId(grade.getId());
                            courseSchedulingDetail.setGradeName(grade.getName());
                            //老师
                            courseSchedulingDetail.setTeacherId(courseSchedulingRedo.getTeacherId());
                            courseSchedulingDetail.setTeacherName(teacher.getName());
                            //助教
                            courseSchedulingDetail.setAssistantId(courseSchedulingRedo.getAssistantId());
                            if(assistant !=null){
                                courseSchedulingDetail.setAssistantName(assistant.getName());
                            }

                            //教室
                            courseSchedulingDetail.setClassRoomId(courseSchedulingRedo.getClassRoomId());
                            courseSchedulingDetail.setClassRoomName(classRoom.getName());
                            //科目
                            courseSchedulingDetail.setSubjectsId(course.getSubjectsId());
                            if(subjects != null){
                                courseSchedulingDetail.setSubjectsName(subjects.getName());
                            }

                            //课程
                            courseSchedulingDetail.setCourseId(grade.getCourseId());
                            courseSchedulingDetail.setCourseName(course.getName());

                            courseSchedulingDetailList.add(courseSchedulingDetail);
                            count--;
                        }
                        if(count == 0){
                            flag = false;
                        }
                        i++;
                    }
                }
                if(courseSchedulingDetailList.size()>0){
                    iCourseSchedulingDetailService.saveBatch(courseSchedulingDetailList,courseSchedulingDetailList.size());
                }
            }
        }


        return true;
    }



}
